package com.vrv.vap.baseline.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.vrv.vap.baseline.entity.AssetTypeSno;
import com.vrv.vap.baseline.mapper.AssetTypeSnoMapper;
import com.vrv.vap.baseline.util.FileOperationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Service
public class AssetTypeSnoImportService {
    private static final Logger log = LoggerFactory.getLogger(AssetTypeSnoImportService.class);
    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
    
    @Autowired
    private AssetTypeSnoMapper assetTypeSnoMapper;
    
    @Autowired
    private FileOperationUtil fileOperationUtil;
    
    /**
     * 处理导入ZIP文件
     * @param file 上传的ZIP文件
     * @return 导入的记录数
     * @throws IOException 如果文件处理过程中发生错误
     */
    @Transactional(rollbackFor = Exception.class)
    public int importFromZip(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        
        // 创建临时目录用于解压文件
        String extractDir = TEMP_DIR + File.separator + UUID.randomUUID().toString();
        Path extractPath = Paths.get(extractDir);
        Files.createDirectories(extractPath);
        
        try {
            // 解压ZIP文件
            List<String> excelFiles = extractZipFile(file, extractPath);
            if (excelFiles.isEmpty()) {
                throw new IllegalArgumentException("ZIP文件中没有找到Excel文件");
            }
            
            // 处理所有Excel文件并导入数据
            int totalImported = 0;
            for (String excelFile : excelFiles) {
                totalImported += importFromExcel(excelFile);
            }
            
            return totalImported;
        } finally {
            // 清理临时文件
            try {
                Files.walk(extractPath)
                        .sorted((a, b) -> b.compareTo(a)) // 逆序，先删除文件，再删除目录
                        .forEach(path -> {
                            try {
                                Files.delete(path);
                            } catch (IOException e) {
                                log.warn("无法删除临时文件: {}", path, e);
                            }
                        });
            } catch (IOException e) {
                log.warn("清理临时文件失败", e);
            }
        }
    }
    
    /**
     * 解压ZIP文件并返回所有Excel文件的路径
     * @param zipFile ZIP文件
     * @param extractPath 解压目标路径
     * @return Excel文件路径列表
     * @throws IOException 如果解压过程中发生错误
     */
    private List<String> extractZipFile(MultipartFile zipFile, Path extractPath) throws IOException {
        List<String> excelFiles = new ArrayList<>();
        
        try (ZipInputStream zipInputStream = new ZipInputStream(zipFile.getInputStream())) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (!entry.isDirectory() && (entry.getName().endsWith(".xlsx") || entry.getName().endsWith(".xls"))) {
                    // 构建文件路径
                    Path filePath = extractPath.resolve(entry.getName());
                    
                    // 确保父目录存在
                    Files.createDirectories(filePath.getParent());
                    
                    // 写入文件
                    Files.copy(zipInputStream, filePath);
                    
                    excelFiles.add(filePath.toString());
                    log.info("解压Excel文件: {}", filePath);
                }
                zipInputStream.closeEntry();
            }
        }
        
        return excelFiles;
    }
    
    /**
     * 从Excel文件导入数据
     * @param excelFilePath Excel文件路径
     * @return 导入的记录数
     */
    private int importFromExcel(String excelFilePath) {
        final int[] count = {0};
        
        try {
            EasyExcel.read(excelFilePath, AssetTypeSno.class, new PageReadListener<AssetTypeSno>(dataList -> {
                for (AssetTypeSno assetTypeSno : dataList) {
                    // 检查数据有效性
                    if (isValidData(assetTypeSno)) {
                        // 检查是否已存在相同GUID的记录
                        AssetTypeSno existingRecord = assetTypeSnoMapper.selectByGuid(assetTypeSno.getGuid());
                        if (existingRecord != null) {
                            // 更新现有记录
                            assetTypeSnoMapper.update(assetTypeSno);
                        } else {
                            // 插入新记录
                            assetTypeSnoMapper.insert(assetTypeSno);
                        }
                        count[0]++;
                    }
                }
                log.info("成功导入{}条记录", count[0]);
            })).sheet().doRead();
            
            return count[0];
        } catch (Exception e) {
            log.error("导入Excel数据失败: {}", excelFilePath, e);
            throw new RuntimeException("导入Excel数据失败", e);
        }
    }
    
    /**
     * 验证数据有效性
     * @param assetTypeSno 资产类型数据
     * @return 是否有效
     */
    private boolean isValidData(AssetTypeSno assetTypeSno) {
        return assetTypeSno != null && StringUtils.hasText(assetTypeSno.getGuid());
    }
}